package com.wondersgroup.tjfx.common.resultHandler;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Component("radar")
public class ChartRadarResultHandler implements ResultSetExtractor<JSONObject> {

	private boolean isNumber(String value) {
		return Pattern.matches("\\d+|\\d+\\.\\d+", value);
	}

	@Override
	public JSONObject extractData(ResultSet rs) throws SQLException, DataAccessException {
		List<String> columnNameList = new ArrayList<String>();
		JSONObject ro = new JSONObject();
		ro.put("state", "true");
		JSONObject json = new JSONObject();
		ResultSetMetaData rm = null;
		rm = rs.getMetaData();
		JSONArray indicator = new JSONArray();
		int length = 0;
		double max = 0d;
		while (rs.next()) {
			JSONObject jo = new JSONObject();
			for (int i = 0; i < rm.getColumnCount(); i++) {
				/* 取字段名 */
				String columnName = rm.getColumnLabel(i + 1);
				columnName = columnName.toUpperCase();
				columnNameList.add(columnName);

				// 旧版本配置有id和key列，新版本不需要，忽略
				if ("ID".equals(columnName) || "KEY".equals(columnName))
					continue;

				/* 取值 */
				String value = rs.getString(i + 1);
				value = value == null ? "" : value;
				if ("NAME".equals(columnName)) {
				} else {
					if (isNumber(value)) {
						// 获取最大值
						double v = Double.valueOf(value);
						max = Math.max(max, v);
					}
					if (json.containsKey(columnName)) {
						JSONArray ar = json.getJSONArray(columnName);
						ar.add(value);
					} else {
						JSONArray ar = new JSONArray();
						ar.add(value);
						json.put(columnName, ar);
					}
				}
			}
			jo.put("name", rs.getString("NAME"));
			// jo.put("max", Math.ceil( max * 1.1));
			indicator.add(jo);
			length++;
		}
		Long m = getMax(max);
		String maxCs = getCs(m);
		m = m/Long.parseLong(maxCs);
		for (int i = 0; i < indicator.size(); i++) {
			JSONObject jo = indicator.getJSONObject(i);
			jo.put("max", m);
		}
		json.put("indicator", indicator);
		ro.putAll(json);
		if (length == 0) {
			ro.put("state", "kong");
		}
		columnNameList = removeDuplicate(columnNameList);
		columnNameList.remove("NAME");
		String cs = "";
		try {
			for(int i=0;i<columnNameList.size();i++){
				String key = columnNameList.get(i);
				String value = ro.getString(key);
				cs = average(value);
				ro.put(key, conversion(cs,value));
			}
		} catch (Exception e) {
			throw new SQLException("查询结果应为数值的列得到其他字符." + e.getLocalizedMessage());
		}
		String dw = getDw(cs);
		ro.put("DW", dw);
		return ro;
	}

	/**
	 * 求最大值 <br>
	 * 100以内，最大值为10 或 100 <br>
	 * 100以上，每次在当前数量级自加,如大余100则比较200，大余1000则比较2000
	 * 
	 * @param value
	 * @return
	 */
	private Long getMax(double value) {
		boolean abs = value >= 0;
		double absValue = Math.abs(value);
		long max = 0;
		if (absValue <= 10) {
			max = 10;
		} else if (absValue <= 100) {
			max = 100;
		} else {
			int i = 2;
			boolean flag = true;
			while (flag) {
				long m = (long) Math.pow(10, i++);
				for (int j = 1; j <= 9; j++) {
					if (absValue <= (max = m * j)) {
						flag = false;
						break;
					}
				}
			}
		}
		return abs ? max : -1 * max;
	}

	/**
	 * 删除重复key
	 * @param list
	 * @return
	 */
	public List<String> removeDuplicate(List<String> list)   { 
	   for(int i = 0 ;i<list.size()-1;i++)   { 
	    for(int j = list.size()-1 ;j>i;j--)   { 
	      if(list.get(j).equals(list.get(i)))   { 
	        list.remove(j); 
	      } 
	    } 
	  } 
	  return list; 
	} 
	
	/**
	 * 除数
	 * @param str
	 * @return
	 */
	public static String average(String str) {
		String[] array = str.substring(1, str.length()-1).replaceAll("\"", "").split(",");
		String result = "1";
		double temp = 0;
		double sum = 0;
		for (int i = 0; i < array.length; i++) {
			sum = sum + Double.parseDouble(array[i]);
		}
		temp = sum / array.length;
		if(temp>10000){
			result = "10000";
		}else if(temp>100000000){
			result = "100000000";
		}
		return result;
	}
	
	/**
	 * 获得除数
	 * @param temp
	 * @return
	 */
	private String getCs(long temp){
		String result = temp + "";
		if(temp>10000){
			result = "10000";
		}else if(temp>100000000){
			result = "100000000";
		}
		return result;
	}
	
	/**
	 * 获得转换单位后的数组
	 * @param jh
	 * @param str
	 * @return
	 */
	private JSONArray conversion(String jh,String str){
		JSONArray ar = new JSONArray();
		DecimalFormat df = new DecimalFormat("#.###");
		String[] value = str.substring(1, str.length()-1).replaceAll("\"", "").split(",");
		for(int i=0;i<value.length;i++){
			String temp = value[i];
			double val = Double.parseDouble(temp)/Double.parseDouble(jh);
			ar.add(df.format(val));
		}
		return ar;
	}
	
	/**
	 * 获得单位
	 * @param jh
	 * @return
	 */
	private String getDw(String jh){
		String result = "";
		if("10000".equals(jh)){
			result = "万";
		}else if("100000000".equals(jh)){
			result = "亿";
		}
		return result;
	}
	
}
